package com.ruoyi.system.service.impl;

import com.ruoyi.system.mapper.AgoniProductMapper;
import com.ruoyi.system.mapper.AgoniTransactionRecordMapper;
import com.ruoyi.system.mapper.AgoniUserMapper;
import com.ruoyi.system.pojo.dto.AcceptTransactionDTO;
import com.ruoyi.system.pojo.entity.Product;
import com.ruoyi.system.pojo.entity.TransactionRecord;
import com.ruoyi.system.pojo.entity.User;
import com.ruoyi.system.pojo.dto.BuyerCreateTransactionDTO;
import com.ruoyi.system.pojo.vo.TransactionRecordUserVO;
import com.ruoyi.system.service.IAgoniTransactionRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class IAgoniTransactionRecordServiceImpl implements IAgoniTransactionRecordService {

    @Autowired
    private AgoniTransactionRecordMapper agoniTransactionRecordMapper;

    @Autowired
    private AgoniProductMapper agoniProductMapper;

    @Autowired
    private AgoniUserMapper agoniUserMapper;


    /**
     * 买家提出交易申请
     * @return
     */
    @Override

    public int buyerCreateTransaction(BuyerCreateTransactionDTO buyerCreateTransactionDTO, Long buyerId) {
        int result=1;
        /**
         * 1,检查商品库存是否足够
         * 2,创建交易记录
         */
        long productId=buyerCreateTransactionDTO.getProductId();
        Product product=agoniProductMapper.selectProductById(productId);

        if (product.getStock()<=0){

            return 0;
        }
        //获取卖家id
        Long sellerId=agoniTransactionRecordMapper.selectSellerIdByStoreId(buyerCreateTransactionDTO.getStoreId());
        List<Integer> transactionLocation=buyerCreateTransactionDTO.getTransactionLocation();
        //转换成字符串
        String transactionLocationStr=transactionLocation.toString();
        //创建交易记录
        TransactionRecord transactionRecord=new TransactionRecord();
        transactionRecord.setBuyerId(Math.toIntExact(buyerId));
        transactionRecord.setSellerId(Math.toIntExact(sellerId));
        transactionRecord.setProductId(Math.toIntExact(productId));
        transactionRecord.setPrice(product.getPrice());
        transactionRecord.setBuyerConfirmation(1);
        transactionRecord.setSellerConfirmation(0);
        //交易状态（如：1=已完成、2=等待卖家确认、3=已取消，4等待买家支付等）
        transactionRecord.setStatus(2);
        transactionRecord.setTransactionDate(buyerCreateTransactionDTO.getTransactionTime());
        transactionRecord.setTransactionAddress(transactionLocationStr);
        transactionRecord.setNotes(buyerCreateTransactionDTO.getRemark());

        log.info("创建交易记录："+transactionRecord.toString());
        int insertResult=agoniTransactionRecordMapper.insertTransactionRecord(transactionRecord);
        if (insertResult==0){
            result=0;
        }
        //更新商品库存
        product.setStock(product.getStock()-1);
      int updateResult= agoniProductMapper.updateProduct(product);
      if (updateResult==0){
          return 0;
      }


        //将记录的可交易地点信息，解析插入redis缓存中
        List<Integer> transactionLocationisd=buyerCreateTransactionDTO.getTransactionLocation();




        return result;
    }

    @Override
    public List<TransactionRecordUserVO> getTransactionRecordByToken(long userId) {


        List<TransactionRecord> transactionRecordList=agoniTransactionRecordMapper.selectTransactionRecordBySellerId(userId);
        if (transactionRecordList==null){
            return null;
        }



        log.info("获取交易记录："+transactionRecordList.toString());
        List<TransactionRecordUserVO> transactionRecordUserVOList=new ArrayList<>();
        for(TransactionRecord transactionRecord:transactionRecordList){

            //获取买家信息
            User buyer=agoniUserMapper.selectUserById(Long.valueOf(transactionRecord.getBuyerId()));
            //获取卖家信息
            User seller=agoniUserMapper.selectUserById(Long.valueOf(transactionRecord.getSellerId()));
            //获取商品信息
            Product product=agoniProductMapper.selectProductById(transactionRecord.getProductId());
            //转换交易记录
            TransactionRecordUserVO userVO = TransactionRecordUserVO.builder()
                    .transactionRecordId(transactionRecord.getId())
                    .productId(transactionRecord.getProductId())
                    .buyerId(transactionRecord.getBuyerId())
                    .buyerName(buyer.getUsername())
                    .sellerId(transactionRecord.getSellerId())
                    .productName(product.getName())

                    .transactionDate(transactionRecord.getTransactionDate())
                    .transactionAddress(transactionRecord.getTransactionAddress())
                    .price(transactionRecord.getPrice())
                    .quantity(transactionRecord.getQuantity())
                    .status(transactionRecord.getStatus())
                    .paymentMethod(transactionRecord.getPaymentMethod())
                    .buyerConfirmation(transactionRecord.getBuyerConfirmation())
                    .sellerConfirmation(transactionRecord.getSellerConfirmation())
                    .notes(transactionRecord.getNotes())
                    .build();

            transactionRecordUserVOList.add(userVO);
            log.info("转换交易记录："+userVO.toString());
            log.info("记录",transactionRecordUserVOList.toString());
        }

        return transactionRecordUserVOList;
    }

    @Override
    public List<TransactionRecordUserVO> getMyBuyRecordByToken(long userId) {
        List<TransactionRecord> transactionRecordList=agoniTransactionRecordMapper.selectTransactionRecordByBuyerId(userId);
        if (transactionRecordList==null){
            return null;
        }
        log.info("获取交易记录："+transactionRecordList.toString());
        List<TransactionRecordUserVO> transactionRecordUserVOList=new ArrayList<>();
        for(TransactionRecord transactionRecord:transactionRecordList){

            //获取买家信息
            User buyer=agoniUserMapper.selectUserById(Long.valueOf(transactionRecord.getBuyerId()));
            //获取卖家信息
            User seller=agoniUserMapper.selectUserById(Long.valueOf(transactionRecord.getSellerId()));
            //获取商品信息
            Product product=agoniProductMapper.selectProductById(transactionRecord.getProductId());
            //转换交易记录
            TransactionRecordUserVO userVO = TransactionRecordUserVO.builder()
                    .transactionRecordId(transactionRecord.getId())
                    .productId(transactionRecord.getProductId())
                    .buyerId(transactionRecord.getBuyerId())
                    .buyerName(buyer.getUsername())
                    .sellerId(transactionRecord.getSellerId())
                    .productName(product.getName())
                    .sellerName(seller.getUsername())
                    .transactionDate(transactionRecord.getTransactionDate())
                    .transactionAddress(transactionRecord.getTransactionAddress())
                    .price(transactionRecord.getPrice())
                    .quantity(transactionRecord.getQuantity())
                    .status(transactionRecord.getStatus())
                    .paymentMethod(transactionRecord.getPaymentMethod())
                    .buyerConfirmation(transactionRecord.getBuyerConfirmation())
                    .sellerConfirmation(transactionRecord.getSellerConfirmation())
                    .notes(transactionRecord.getNotes())
                    .build();

            transactionRecordUserVOList.add(userVO);
            log.info("转换交易记录："+userVO.toString());
            log.info("记录",transactionRecordUserVOList.toString());
        }

        return transactionRecordUserVOList;
    }

    /**
     * 我的购买记录
     * @param id
     * @return
     */














    //拒绝交易

    @Override
    public int rejectTransaction(Long id) {

        TransactionRecord transactionRecord=agoniTransactionRecordMapper.selectTransactionRecordById(id);
        if (transactionRecord==null){
            return 0;
        }
        Product product=agoniProductMapper.selectProductById(transactionRecord.getProductId());

        //更新商品库存
        product.setStock(product.getStock()+1);
        int updateProductResult= agoniProductMapper.updateProduct(product);
        if (updateProductResult==0){
            return 0;
        }

        transactionRecord.setSellerConfirmation(2);
        transactionRecord.setStatus(3);
        int updateResult=agoniTransactionRecordMapper.updateTransactionRecord(transactionRecord);
        if (updateResult==0){
            return 0;
        }

        return 1;
    }

    //确认交易

    @Override
    public int acceptTransaction(Long id) {
        TransactionRecord transactionRecord=agoniTransactionRecordMapper.selectTransactionRecordById(id);
        if (transactionRecord==null){
            return 0;
        }
        transactionRecord.setSellerConfirmation(1);
        transactionRecord.setStatus(4);
        int updateResult=agoniTransactionRecordMapper.updateTransactionRecord(transactionRecord);
        if (updateResult==0){
            return 0;
        }

        return 1;
    }

    //带数据


    @Override
    public int acceptTransactionByData(AcceptTransactionDTO acceptTransactionDTO) {
        TransactionRecord transactionRecord=agoniTransactionRecordMapper.selectTransactionRecordById(Long.valueOf(acceptTransactionDTO.getTransactionRecordId()));
        if (transactionRecord==null){
            return 0;
        }
        transactionRecord.setSellerConfirmation(1);
        transactionRecord.setStatus(4);
        List<Integer> transactionLocation= Collections.singletonList(acceptTransactionDTO.getTransactionAddressId());
        transactionRecord.setTransactionAddress(String.valueOf(transactionLocation));
        int updateResult=agoniTransactionRecordMapper.updateTransactionRecord(transactionRecord);
        if (updateResult==0){
            return 0;
        }

        return 1;
    }
}
